package com.allqj.sfx.ddd.member.infrastructure.converter;

import com.allqj.sfx.ddd.member.domain.entity.flow.FlowTaskDef;
import com.allqj.sfx.ddd.member.infrastructure.dao.FlowTaskDefDAO;
import com.allqj.sfx.ddd.member.infrastructure.po.FlowTaskDefDO;
import com.allqj.sfx.infrastructure.converter.DataConverter;
import com.allqj.sfx.infrastructure.utils.JsonUtil;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Optional;

/**
 * @author sjw
 * @className FlowTaskDefConverter
 * @date 2022/7/20 15:37
 * @description: FlowDef&FlowDefDO转换器
 */
public class FlowTaskDefConverter implements DataConverter<FlowTaskDef, FlowTaskDefDO, FlowTaskDefDAO> {

    // 转换器实例
    public static FlowTaskDefConverter INSTANCE = new FlowTaskDefConverter();


    @Override
    public FlowTaskDef do2Entity(FlowTaskDefDO flowTaskDefDO) {
        if (flowTaskDefDO == null)
            return null;
        FlowTaskDef flowTaskDef = new FlowTaskDef();
        BeanUtils.copyProperties(flowTaskDefDO, flowTaskDef);
        flowTaskDef.setApproverDef(JsonUtil.jsonToObject(flowTaskDefDO.getApproverDef(), new TypeToken<List<Integer>>() {
        }.getType()));
        return flowTaskDef;
    }

    @Override
    public FlowTaskDefDO entity2Do(FlowTaskDef flowTaskDef) {
        if (flowTaskDef == null) return null;
        FlowTaskDefDO flowTaskDefDO = new FlowTaskDefDO();
        BeanUtils.copyProperties(flowTaskDef, flowTaskDefDO);
        flowTaskDefDO.setApproverDef(JsonUtil.objectToJson(flowTaskDef.getApproverDef()));
        return flowTaskDefDO;
    }

    @Override
    public FlowTaskDefDO entity2Do(FlowTaskDef flowTaskDef, FlowTaskDefDAO flowTaskDefDAO) {
        if (flowTaskDef == null) return null;
        if (flowTaskDef.getId() == null) {
            return entity2Do(flowTaskDef);
        }
        Optional<FlowTaskDefDO> flowTaskDefDOOptional = flowTaskDefDAO.findById(flowTaskDef.getId());
        FlowTaskDefDO flowTaskDefDO = null;
        if (flowTaskDefDOOptional.isPresent()) {
            flowTaskDefDO = flowTaskDefDOOptional.get();
            flowTaskDefDO.setFlowDefId(flowTaskDef.getFlowDefId());
            flowTaskDefDO.setApproverType(flowTaskDef.getApproverType());
            flowTaskDefDO.setApproverDef(JsonUtil.objectToJson(flowTaskDef.getApproverDef()));
            flowTaskDefDO.setTaskStep(flowTaskDef.getTaskStep());
            flowTaskDefDO.setModiferId(flowTaskDef.getModiferId());
            flowTaskDefDO.setModifyTime(flowTaskDef.getModifyTime());
        }
        return flowTaskDefDO;
    }
}
